//
//  ST_EditMyInfoViewController.swift
//  btvideo
//
//  Created by mac on 2020/1/6.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SwiftyJSON
//import NSGIF

//8_个人中心_编辑个人资料(空)-Controller
class ST_EditMyInfoViewController: ST_BTLightBarViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("编辑个人资料")
        
        view.backgroundColor = Color.white
        
        view.addSubview(guidance_header)
        guidance_header.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(0)
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(0)
            make.bottom.right.left.equalToSuperview()
        }
        
        guidance_header.edit_closure = {[weak self] in
            
            guard let result = self?.queryItem(by: "personal_desc") else {
                return
            }
            
            self?.edit_my_introduce_handle(sourceIndexPath: result.indexPath)
            
        }
        
        create_will_modify_data()
    }
    
    override var hidden_right_btn: Bool {
        set {
            super.hidden_right_btn = newValue
        }
        get {
            return false
        }
    }
    
    func save_modify_handle(){
        
        if modified_map.isEmpty{
            print("没有更改")
            
            self.goback_previous_controller()
            return
        }
        
        
        ST_BTUserInfoManager.shared.judge_account_frozen().withUnretained(self).subscribe(onNext: { own,_ in
            
            let param = own.modified_map
            
            
            
            own.modified_map.removeAll()
            
            JVrequest(PH.modifyUserGeneralInfoApi,parameters:param,success: { (json) in
                
                NotificationCenter.default.post(name: NSNotification.Name.my_pairs_user_info_updated, object: nil)
                
            }) { (code, err) in
                
                own.toast(text: err)
            }
            
            
       }).disposed(by: rx.disposeBag)
        
        
        
        
    }
    
    //    MARK: - Album modify block
    var append_closure:((ST_PairsShareParticularModel)->())?
    
    var sort_closure:(([String])->())?
    
//    MARK: - Properties
    fileprivate lazy var sign_attributes:[NSAttributedString.Key : Any] = {
        
        let paragraph = NSMutableParagraphStyle()
        
        paragraph.lineSpacing = 10
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.44, alpha: 1),.paragraphStyle:paragraph]
        
        return attr
    }()
    
       
        
    
    fileprivate lazy var guidance_header:ST_EditMyInfoGuidanceHeader = {
       let control = ST_EditMyInfoGuidanceHeader()
        return control
    }()
    
    fileprivate lazy var tableView:UITableView = {
            
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.grouped)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 50 , right: 0)
        
        control.delegate = self
        
        control.dataSource = self
        
        control.register(headerFooterViewClassWith: ST_EditMyInfoSectionView.self)
        
        control.register(cellWithClass: ST_EditGeneralInfoCell.self)
        
        control.register(cellWithClass: ST_EditGeneralTextCell.self)
        
        control.register(cellWithClass: ST_EditGeneralEmptyTextCell.self)
        
        control.register(cellWithClass: ST_EditMyGardenCell.self)
        
        control.register(cellWithClass: ST_EditMyVoiceSignCell.self)
        
        control.separatorStyle = .none
        
        control.backgroundColor = Color.white
    
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        control.tableHeaderView = self.headerView
        
        return control
    }()
    
    fileprivate lazy var headerView:ST_EditMyInfoHeaderView = {
       
        let control = ST_EditMyInfoHeaderView(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: header_height))
        
        control.phDelegate = self
        
        control.pushClosure = {[weak self] in
            
            let vc = ST_MyPhotoViewController()
            
            vc.append_closure = { m in
                self?.append(model: m)
                
                self?.append_closure?(m)
            }
            
            vc.sort_closure = { urls in
                self?.sort(by: urls)
                self?.sort_closure?(urls)
            }
            
            self?.navigationController?.pushViewController(vc)
        }
        
        return control
    }()
    
    
    
    fileprivate var header_height = 100.cgFloat{
        didSet{
            
            self.headerView.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: header_height))
            
            self.headerView.pairsHeader.frame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: ScreenWidth, height: header_height))
            
            self.tableView.tableHeaderView = self.headerView
        }
    }
    

    fileprivate lazy var data_array = [[ST_EditMyInfoCellData]]()
    
    fileprivate lazy var header_text_array = [String]()
 
    fileprivate var voice_sign_review_status = 0
//    发送给后台更改的值
    var modified_map = [String:String]()
    
//    MARK: - Create Data
    fileprivate var birthDay:Date?
    
    fileprivate var album = [ST_PairsShareParticularModel](){
        didSet{
            self.headerView.setUp(data_array: album)
            self.headerView.click_btn.isHidden = false
        }
    }
    
    fileprivate func fetch_display_value(json:JSON,key:String)->String?{
        
//            首先审核中
                  if let p = json[key + "_auditing"].string,p.count > 0{
                      return p
                  }
      //            其次正式
                  else if let p = json[key].string,p.count > 0{
                    return p
                  }
        return nil
    }
    
    fileprivate func create_will_modify_data(){
        
        JVrequest(PH.fetchUserGeneralInfoApi, success: { (json) in
            
            let data = json["data"]
            
            print("拼接数据啦：",data)
            
            self.album = ST_PairsShareParticularModel.describe(json_array: data["album"].arrayValue)
        
            if let first = self.album.first{
                
                self.header_height = first.displayHeight
                
            }
            
            
            var list = [[ST_EditMyInfoCellData]]()
            
                
            
            if let str = self.fetch_display_value(json: data, key: "sign"){

                let attrString = NSMutableAttributedString(string: str)
                    
                attrString.addAttributes(self.sign_attributes, range: NSRange(location: 0, length: attrString.length))
                    
                let attrHeight = attrString.height(withConstrainedWidth: ScreenWidth - 16-15)
                
                let cellHeight = attrHeight + 17 + 4
                
                let m0 = EditGeneralTextCellModel_Copy(attributedText: attrString, modifyKey: "sign",cellHeight: cellHeight)
                
                list.append([ST_EditMyInfoCellData.text(value: m0)])
                
            }else{
                
                let m0 = EditGeneralEmptyTextCellModel_Copy(reminderString: "立即填写签名", modifyKey: "sign", cellHeight: 95)
                
                list.append([ST_EditMyInfoCellData.empty(value: m0)])
                
            }
            
            
            if let str = self.fetch_display_value(json: data, key: "personal_desc"){
                
                let attrString = NSMutableAttributedString(string: str)
                    
                attrString.addAttributes(self.sign_attributes, range: NSRange(location: 0, length: attrString.length))
                    
                let attrHeight = attrString.height(withConstrainedWidth: ScreenWidth - 16-15)
                
                let cellHeight = attrHeight + 17 + 4
                
                let m0 = EditGeneralTextCellModel_Copy(attributedText: attrString, modifyKey: "personal_desc",cellHeight: cellHeight)
                
                list.append([ST_EditMyInfoCellData.text(value: m0)])
                
                self.tableView.snp.updateConstraints { (make) in
                    make.top.equalTo(self.own_navigation_bar.snp.bottom).offset(0)
                }
                
            }else{
                
                let m0 = EditGeneralEmptyTextCellModel_Copy(reminderString: "立即填写个人简介", modifyKey: "personal_desc", cellHeight: 95)
                
                list.append([ST_EditMyInfoCellData.empty(value: m0)])
                
                self.tableView.snp.updateConstraints { (make) in
                    make.top.equalTo(self.own_navigation_bar.snp.bottom).offset(80)
                }
                
            }
            
            
            self.header_text_array = ["签名","个人介绍"]
            
            
            if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .female{
                self.header_text_array.append("语音签名")
                
                self.voice_sign_review_status = data["voice_sign_status"].intValue
                
                if let voiceSignUrl = data["voice_sign_url"].url{
    
                    list.append([ST_EditMyInfoCellData.voiceSign(value: ST_EditMyVoiceSignCellModel_Copy(url: voiceSignUrl, duration: data["duration"].intValue, modifyKey: "voice_sign", cellHeight: 60))])
    
                }else{
    
                    let m0 = EditGeneralEmptyTextCellModel_Copy(reminderString: "立即录制签名", modifyKey: "voice_sign", cellHeight: 95)
    
                    list.append([ST_EditMyInfoCellData.empty(value: m0)])
                }
            }
            
            if let url = data["room_cover"].string?.compress_small_image(width: 60*3).url{
                
                self.header_text_array.append("房间封面")
                
                list.append([ST_EditMyInfoCellData.roomGarden(value: ST_EditMyGardenCellModel(imageUrl: url, img: nil, modifyKey: "video_cover", cellHeight: 92+20))])
                
            }else if data["can_upload"].boolValue{
                
                let m0 = EditGeneralEmptyTextCellModel_Copy(reminderString: "立即上传封面", modifyKey: "video_cover", cellHeight: 95)
                
                list.append([ST_EditMyInfoCellData.empty(value: m0)])
                
                self.header_text_array.append("房间封面")
                
            }
            
            self.header_text_array.append("个人资料")
            
            
            
            
            var infoSection = [ST_EditMyInfoCellData]()
            
            
            if let str = self.fetch_display_value(json: data, key: "nickname"){
                
                infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "昵称", displayValue: str, modifyKey: "nickname")))
                
            }else{
                
                infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "昵称", displayValue: "", modifyKey: "nickname")))
                
            }
            
            
            
            var birthDayStr = ""
            
            if let birth = data["birth"].double{
                let birthDate = Date.init(timeIntervalSince1970:birth)
                self.birthDay = birthDate
                birthDayStr = birthDate.string(withFormat: "yyyy/MM/dd")
            }
            
            infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "生日", displayValue: birthDayStr, modifyKey: "birth")))
            
            
            infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "想要寻求", displayValue: data["personal_want_name"].stringValue, modifyKey: "personal_want",selectedId: data["personal_want"].stringValue)))
            
            
            infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "家乡", displayValue: data["home_town_title"].stringValue, modifyKey: "home_town_title")))
            
            
            infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "身高", displayValue: data["height"].stringValue, modifyKey: "height")))
            
            
            infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "学历", displayValue: data["personal_education_name"].stringValue, modifyKey: "personal_education",selectedId: data["personal_education"].stringValue)))
            
            
            infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "职业", displayValue: data["personal_job_name"].stringValue, modifyKey: "personal_job",selectedId: data["personal_job"].stringValue)))
            
            
            infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "抽烟", displayValue: data["personal_smoke_name"].stringValue, modifyKey: "personal_smoke",selectedId: data["personal_smoke"].stringValue)))
            
            
            infoSection.append(ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "喝酒", displayValue: data["personal_drink_name"].stringValue, modifyKey: "personal_drink",selectedId: data["personal_drink"].stringValue)))
            
            list.append(infoSection)
            
//            var array = [[ST_EditGeneralInfoCellModel]]()
            
            /*
            let dict0 = ST_EditGeneralInfoCellModel()
            dict0.modifyKey = "sign"
            dict0.displayKey = "签名"
            dict0.displayValue = data["sign"].stringValue
            if let str = data["sign_auditing"].string,!str.isEmpty{
                dict0.displayValue = str
            }
            
            dict0.create_display_attribute_string()
            
            array.append([dict0])
            
            let dict1 = ST_EditGeneralInfoCellModel()
            dict1.modifyKey = "personal_desc"
            dict1.displayKey = "个人介绍"
            dict1.displayValue = data["personal_desc"].stringValue
            if let str = data["personal_desc_auditing"].string,!str.isEmpty{
                dict1.displayValue = str
            }
            
            
            dict1.create_display_attribute_string()
            array.append([dict1])
            
             
             */
            
//            array.append([dict20,dict21,dict222,dict22,dict23,dict24,dict25,dict26,dict27])
            
            
            self.data_array = list
            
            self.tableView.reloadData()
    
        }) { (code, err) in
            print("新街口访问失败 :",err)
        }
        
        
        
    }
//    MARK: - Private Method
    fileprivate func edit_my_introduce_handle(sourceIndexPath:IndexPath,currentText:String = ""){
        
        let vc = ST_EditMyIntroViewController()
                        
        vc.display_text = currentText
        
        vc.update_value_closure = {[weak self] m in

            guard let strongSelf = self else {
                return
            }
            
            let attrString = NSMutableAttributedString(string: m)
                
            attrString.addAttributes(strongSelf.sign_attributes, range: NSRange(location: 0, length: attrString.length))
                
            let attrHeight = attrString.height(withConstrainedWidth: ScreenWidth - 16-15)
            
            let cellHeight = attrHeight + 17 + 4
            
            let m0 = EditGeneralTextCellModel_Copy(attributedText: attrString, modifyKey: "personal_desc",cellHeight: cellHeight)
            
            if self?.data_array[safe: sourceIndexPath.section]?[safe: sourceIndexPath.item] != nil{
                
                self?.data_array[sourceIndexPath.section][sourceIndexPath.item] = ST_EditMyInfoCellData.text(value: m0)
                
            }
            
            
            strongSelf.modified_map.updateValue(m, forKey: "personal_desc")
//
            strongSelf.save_modify_handle()
            
            
            strongSelf.tableView.reloadData {
                if m.isEmpty{
                    strongSelf.tableView.snp.updateConstraints { (make) in
                        make.top.equalTo(strongSelf.own_navigation_bar.snp.bottom).offset(80)
                    }
                }else{
                    strongSelf.tableView.snp.updateConstraints { (make) in
                        make.top.equalTo(strongSelf.own_navigation_bar.snp.bottom).offset(0)
                    }
                }
            }
        }
        
        self.navigationController?.pushViewController(vc)
        
        
    }
     
    private func record_voice_sign(){
        
        let vc = ST_QuickMessageVoiceViewController(viewModel: ST_QuickMessageVoiceViewModel.recordVoiceSignVMCreator())
        vc.onAdd = { [weak self] in
            
            self?.create_will_modify_data()
            
            NotificationCenter.default.post(name: NSNotification.Name.my_pairs_user_info_updated, object: nil)
        }
        GlobalPresent(toController: vc)
    }
    
    fileprivate func room_cover_pick(){
        
        let vc = ST_JVImagePickerController()
        
        vc.picker_style = .video
        
        vc.overCurrentContext = true
        
        vc.picker_video_closure = {[weak self] url,seconds in
            
            
            main_thread_execute {
                
                self?.show_indeterminate_h_u_d(text: "解析上传中...")
                
            }
            
            back_thread_execute {
                
                let filename = UUID().uuidString+".mp4"
                
                guard var videoPath = SC.push_peculiarity_directory else { return }
                
                videoPath.appendPathComponent(filename)
                
                do {
                    try FileManager.default.copyItem(at: url, to: videoPath)
                } catch (let error) {
                    print("Cannot copy item at \(url) to \(videoPath): \(error)")
                    
                    main_thread_execute {
                        self?.hidden_indeterminate_h_u_d()
                    }
                    return
                }
                
                guard let img = url.get_video_thumbnail_image(),let imgData = img.sd_imageData() else{
                    
                    main_thread_execute {
                        self?.hidden_indeterminate_h_u_d()
                    }
                    return
                }
                
                
                main_thread_execute {
                    
                    guard let result = self?.queryItem(by: "video_cover") else{
                        return
                    }
                    
                        if self?.data_array[safe: result.indexPath.section]?[safe: result.indexPath.item] != nil{
                            
                            
                            
                            self?.data_array[result.indexPath.section][result.indexPath.item] = ST_EditMyInfoCellData.roomGarden(value: ST_EditMyGardenCellModel(imageUrl: nil, img: img, modifyKey: "video_cover", cellHeight: 92+20))
                            
                            self?.tableView.reloadData()
                            
                        }
                    
                }
                
                
                
                let imgKey = img.tian_uploadFileKey()
                
                JVUpload(videoPath: videoPath.path, coverImage: imgData, imageCloudKey: imgKey, videoCloudKey: filename) { _ in
                    
                    
                } success: { str0, str1 in
                    
                    self?.upload_room_cover(videoKey: str1, imageKey: str0, size: img.size, duration: seconds.int.string)
                        
                    
                } failure: { code, err in
                    
                    main_thread_execute {
                        self?.toast(text: err)
                    }
                }
                
                
                /*
                NSGIF.createGIFfromURL(url, withFrameCount: 30, delayTime: 0, loopCount: 1) { giftUrl in
                    
                    guard let gif = giftUrl, let gifData = try? Data.init(contentsOf: gif),let gifSDImg = UIImage.sd_image(with: gifData),let gifCompressData = gifSDImg.sd_imageData(as: gifSDImg.sd_imageFormat, compressionQuality: 0.3) else{
                        
                        main_thread_execute {
                            self?.hidden_indeterminate_h_u_d()
                        }
                        
                        return
                    }
                    
                    let imgKey = img.tian_uploadFileKey()
                    
                    main_thread_execute {
                        
                        self?.show_indeterminate_h_u_d(text: "上传中...")
                        
                    }
                    
                    
                    
                    
                    JVUpload(videoPath: videoPath.path, coverImage: imgData, imageCloudKey: imgKey, videoCloudKey: filename) { _ in
                        
                        
                    } success: { str0, str1 in
                        
                        let gifKey = gif.lastPathComponent
                        
                        
                        JVUpload(fileKey:gifKey,data: gifCompressData) { _ in
                            
                            
                            
                        } success: { _ in
                            
                            self?.upload_room_cover(gifKey: gifKey, videoKey: str1, imageKey: str0, size: img.size, duration: seconds.int.string)
                            
                            
                        } failure: { code, err in
                            
                            main_thread_execute {
                                
                                self?.toast(text: err)
                            }
                        }

                        
                        
                        
                    } failure: { code, err in
                        
                        main_thread_execute {
                            self?.toast(text: err)
                        }
                    }

                 
                    
                }
                
                
                */
                
            }
            
        }
        
        GlobalPresent(toController: vc)
        
    }
    
    
    fileprivate func upload_room_cover(gifKey:String = "",videoKey:String,imageKey:String,size:CGSize,duration:String){
        
        
        JVrequest(PH.uploadRoomCoverApi,parameters: ["url":imageKey,"video_url":videoKey,"gif_url":gifKey,"video_duration":duration,"width":size.width.int.string,"height":size.height.int.string]) { json in
            
            self.hidden_indeterminate_h_u_d()
            
            NotificationCenter.default.post(name: NSNotification.Name.my_pairs_user_info_updated, object: nil)
            
        } failure: { code, err in
            
            self.toast(text: err)
        }
        
        
    }
    
    fileprivate func edit_single_line_handle(sourceIndexPath:IndexPath,title:String,maxLength:Int,placeholder:String,modifyKey:String,displayKey:String,currentText:String = ""){
        
        let vc =  ST_EditInfoTextFieldController()
        
        vc.title = title
        
        vc.placeholder = placeholder
        
        vc.maxLength = maxLength
        
        vc.display_text = currentText
        
        vc.update_value_closure = {[weak self] m in
            
            self?.modified_map.updateValue(m, forKey: modifyKey)
            
            self?.save_modify_handle()
            
            if self?.data_array[safe: sourceIndexPath.section]?[safe: sourceIndexPath.item] != nil{
                
                if modifyKey == "sign"{
                    
                    let attrString = NSMutableAttributedString(string: m)
                        
                    if let attr = self?.sign_attributes{
                        attrString.addAttributes( attr , range: NSRange(location: 0, length: attrString.length))
                    }
                    
                    let attrHeight = attrString.height(withConstrainedWidth: ScreenWidth - 16-15)
                    
                    let cellHeight = attrHeight + 17 + 4
                    
                    let m0 = EditGeneralTextCellModel_Copy(attributedText: attrString, modifyKey: "sign",cellHeight: cellHeight)
                    
                    self?.data_array[sourceIndexPath.section][sourceIndexPath.item] = ST_EditMyInfoCellData.text(value: m0)
                    
                }else{
                    
                    let m0 = ST_EditGeneralInfoCellModel_Copy(displayKey: displayKey, displayValue: m, modifyKey: modifyKey)
                    
                    self?.data_array[sourceIndexPath.section][sourceIndexPath.item] = ST_EditMyInfoCellData.generalInfo(value: m0)
                }
                
                
                
            }
            
            self?.tableView.reloadData()
            
        }
        
        self.navigationController?.pushViewController(vc)
        
    }
    
    
//    MARK: - Tools
    fileprivate func queryItem(by key:String) -> (indexPath:IndexPath,model:ST_EditMyInfoCellData)? {
        
        for (section,item) in data_array.enumerated(){
            for (row,item_model) in item.enumerated(){
                if item_model.commonValue.modifyKey == key{
                    return (indexPath:IndexPath(row: row, section: section),model:item_model)
                }
            }
        }
        
        return nil
    }
    
//    MARK: - Home Town
    var city:String?
    var province:String?
    
    lazy var homeTownPickerView:ST_BTTwicePickerView = {
            
       let control = ST_BTTwicePickerView()
        
       control.confirm_pick_closure = {[weak self] title,subTitle,indexPath in
           
           if title == subTitle{
            
               var nsTitle = title as NSString
               
               nsTitle = nsTitle.replacingOccurrences(of: "省", with: "") as NSString
               
               nsTitle = nsTitle.replacingOccurrences(of: "市", with: "") as NSString
               
               self?.city = nsTitle as String
               self?.province = nsTitle as String
               
           }else{
            
               var nsTitle = title as NSString
               
               nsTitle = nsTitle.replacingOccurrences(of: "省", with: "") as NSString
               
               nsTitle = nsTitle.replacingOccurrences(of: "市", with: "") as NSString
               
               self?.province = nsTitle as String
               
               var nsSubTitle = subTitle as NSString
               
               nsSubTitle = subTitle.replacingOccurrences(of: "省", with: "") as NSString
               
               nsSubTitle = subTitle.replacingOccurrences(of: "市", with: "") as NSString
               
               self?.city = nsSubTitle as String
               
           }
           
            self?.home_town_pick_action()
        
       }
       
       if let path = Bundle.main.path(forResource: "province", ofType: "json"),let data = NSData.init(contentsOf: URL.init(fileURLWithPath: path)){
           
           let json = try! JSON.init(data: data as Data)
           
           var option_array = [ST_BTTwicePickerViewModel]()
           
           for item in json.arrayValue{
               
               var child = [BTTwicePickerItemViewModel]()
               
               for element in item["city"].arrayValue{
                   
                   let nameItem = BTTwicePickerItemViewModel.init(title: element["name"].stringValue)
                   
                   child.append(nameItem)
                   
               }
               
               let pickerModel = ST_BTTwicePickerViewModel.init(title: item["name"].stringValue, child: child)
               
               option_array.append(pickerModel)
           }
           
           control.option_array = option_array
       }
       
       
        return control
    }()
    
    //    MARK: - date picker
    
    lazy var pickerView:ST_BirthdayPickerView = {
        
        let control = ST_BirthdayPickerView()
        
        control.confirm_pick_closure = {[weak self] date in
            self?.birthday_pick_action(date: date)
        }
        return control
    }()
//    MARK: - stature 身高 picker
    fileprivate lazy var stature_picker_view_datas:[String] = {
        var array = [String]()
        
        for i in 130...200{
            array.append(i.string+"cm")
        }
        return array
    }()
    
    
   
    
    lazy var stature_picker_view:ST_BTOncePickerView = {
            
        let control = ST_BTOncePickerView()
        
        control.option_array = stature_picker_view_datas
        
        control.confirm_pick_closure = {[weak self] str in
            
            guard let result = self?.queryItem(by: "height") else{
                return
            }
            
            switch result.model{
            case .generalInfo(let value):
                
                if self?.data_array[safe: result.indexPath.section]?[safe: result.indexPath.item] != nil{
                    
                    self?.data_array[result.indexPath.section][result.indexPath.item] = ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "身高", displayValue: str, modifyKey: "height"))
                }
                
                let mStr = str.removingSuffix("cm")
                
                self?.modified_map.updateValue(mStr, forKey: "height")
                
                self?.save_modify_handle()
                
                self?.tableView.reloadData()
                 
                break
            default:
                break
            }
                
            
        }
        return control
    }()
    
}

extension ST_EditMyInfoViewController:UITableViewDataSource,UITableViewDelegate{
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return data_array.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 50
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = tableView.dequeueReusableHeaderFooterView(withClass: ST_EditMyInfoSectionView.self)
        
        let indexPath = IndexPath(row: 0, section: section)
        
        let titleText = header_text_array[section]
        if titleText.contains("语音签名") && voice_sign_review_status == 1{
            view.arguments = [titleText,"审核中"]
        }else{
            view.arguments = [titleText]
        }
        
        view.click_closure = {[weak self] text in
            
            switch text {
                
            case "语音签名":
                
                self?.record_voice_sign()
            
            case "签名":
                
                guard let result = self?.queryItem(by: "sign") else {
                    return
                }
                
                switch result.model {
                
                    case .text(let value):
                
                        self?.edit_single_line_handle(sourceIndexPath: result.indexPath, title: "设置签名", maxLength: 24, placeholder: "请输入签名", modifyKey: "sign", displayKey: "签名",currentText:value.attributedText.string)
                        
                case .empty:
                    
                    self?.edit_single_line_handle(sourceIndexPath: result.indexPath, title: "设置签名", maxLength: 24, placeholder: "请输入签名", modifyKey: "sign", displayKey: "签名")
                        
                default:
                    break
                }
                
            case "个人介绍":
                
                guard let result = self?.queryItem(by: "personal_desc") else {
                    return
                }
                
                switch result.model {
                
                    case .text(let value):
                
                        self?.edit_my_introduce_handle(sourceIndexPath: indexPath,currentText: value.attributedText.string)
                        
                    case .empty:
                    
                        self?.edit_my_introduce_handle(sourceIndexPath: indexPath)
                default:
                    break
                }
                
            case "房间封面":
                
                self?.room_cover_pick()
                
            default:
                break
            }
        }
        
        return view
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data_array[safe:section]?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cellModel = self.data_array[safe:indexPath.section]?[safe:indexPath.row] else{
            let cell = tableView.dequeueReusableCell(withClass: ST_EditGeneralInfoCell.self, for: indexPath)
            return cell
        }
        
        switch cellModel {
        case .text(let value):
            
            let cell = tableView.dequeueReusableCell(withClass: ST_EditGeneralTextCell.self, for: indexPath)
            cell.model_copy = value
            return cell
            
        case .empty(let value):
            
            let cell = tableView.dequeueReusableCell(withClass: ST_EditGeneralEmptyTextCell.self, for: indexPath)
            
            cell.model_copy = value
            
            return cell
            
        case .generalInfo(let value):
            
            let cell = tableView.dequeueReusableCell(withClass: ST_EditGeneralInfoCell.self, for: indexPath)
            
            cell.model_copy = value
            
            return cell
            
        case .roomGarden(value: let value):
            
            let cell = tableView.dequeueReusableCell(withClass: ST_EditMyGardenCell.self, for: indexPath)
            
            cell.bind(model: value)
            
            return cell
        case .voiceSign(value: let value):
            
            
            let cell = tableView.dequeueReusableCell(withClass: ST_EditMyVoiceSignCell.self, for: indexPath)
            
            cell.model = value
            
            return cell
            
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        
        if let iCell = cell as? ST_EditMyVoiceSignCell{
            
            iCell.stop_playing()
            
        }
        
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        guard let cellModel = self.data_array[safe:indexPath.section]?[safe:indexPath.row] else{
            return
        }
        
            switch cellModel {
                
                
            case .voiceSign(let value):
                
                record_voice_sign()
            
            case .roomGarden:
                
                room_cover_pick()
                
            case .text(let value):
                
                switch value.modifyKey {
                
                    case "personal_desc":
                        
                        edit_my_introduce_handle(sourceIndexPath: indexPath,currentText: value.attributedText.string)
                        
                        break
                        
                    case "sign":
                                        
                        edit_single_line_handle(sourceIndexPath: indexPath, title: "设置签名", maxLength: 24, placeholder: "请输入签名", modifyKey: "sign", displayKey: "签名",currentText: value.attributedText.string)
                       
                        break
                    
                default:
                    break
                }
                
            
            case .generalInfo(let value):

                switch value.modifyKey {
                
                case "video_cover":
                    
                    room_cover_pick()
                    
                case "birth":
                    
                    self.select_birth_day_action()
                    
                case "nickname":
                    
                    edit_single_line_handle(sourceIndexPath: indexPath, title: "设置昵称", maxLength: 12, placeholder: "请输入昵称", modifyKey: "nickname", displayKey: "昵称", currentText: value.displayValue)
                    
                    
                case "home_town_title":
                    
                    select_home_town_action()
                    
                case "height":
                    
                    select_stature_action()
                    
                case "personal_job":
                    
                    let vc = ST_EditOccupationViewController()
                
                    vc.info_model = (selectedId: value.selectedId , display_text: value.displayValue)
                    
                    vc.update_value_closure = {[weak self] t in
                        
                        self?.modified_map.updateValue(t.selectedId, forKey: "personal_job")
                        
                        self?.save_modify_handle()
                        
                        if self?.data_array[safe: indexPath.section]?[safe: indexPath.item] != nil{
                            
                            let m0 = ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: "职业", displayValue: t.display_text, modifyKey: "personal_job",selectedId: t.selectedId))
                            
                            self?.data_array[indexPath.section][indexPath.item] = m0
                            
                        }
                        
                        self?.tableView.reloadData()
                        
                    }
                    
                    self.navigationController?.pushViewController(vc)
                    
                    break
                    
                default:
                    
                    let vc =  ST_EditMyInfoOptionsController()
                    
                    vc.outsideInfo = (selectedId:value.selectedId ,displayValue:value.displayValue,displayKey:value.displayKey,modifyKey:value.modifyKey)
                    
                    vc.update_value_closure = {[weak self] id , displayValue in
                        
                        self?.modified_map.updateValue(id, forKey: value.modifyKey)
                        
                        self?.save_modify_handle()
                        
                        if self?.data_array[safe: indexPath.section]?[safe: indexPath.item] != nil{
                            
                            let m0 = ST_EditGeneralInfoCellModel_Copy(displayKey: value.displayKey, displayValue: displayValue, modifyKey: value.modifyKey)
//
                            self?.data_array[indexPath.section][indexPath.item] = ST_EditMyInfoCellData.generalInfo(value: m0)
                            
                            self?.tableView.reloadData()
                            
                        }
                        
                    }
                    
                    self.navigationController?.pushViewController(vc)
                    
                    
                    break
                }

                
            case .empty(let value):
                
                switch value.modifyKey {
                
                case "sign":
                    
                    edit_single_line_handle(sourceIndexPath: indexPath, title: "设置签名", maxLength: 24, placeholder: "请输入签名", modifyKey: "sign", displayKey: "签名")
                    
                case "nickname":
                    
                    edit_single_line_handle(sourceIndexPath: indexPath, title: "设置昵称", maxLength: 12, placeholder: "请输入昵称", modifyKey: "nickname", displayKey: "昵称")
                    
                case "personal_desc":
                    
                    edit_my_introduce_handle(sourceIndexPath: indexPath)
                    
                case "video_cover":
                    
                    room_cover_pick()
                    
                    
                case "voice_sign":
                    
                    record_voice_sign()
                    
                default:
                    break
                }
            }
            
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       
        if let cellModel = self.data_array[safe:indexPath.section]?[safe:indexPath.row]?.commonValue{
            
            return cellModel.cellHeight
            
        }
        return 44
        
    }
    
    
}




//MARK: - 选择控件
extension ST_EditMyInfoViewController{
    
    func select_stature_action(){
        
        if self.stature_picker_view.superview == nil {
            
            self.view.addSubview(self.stature_picker_view)
            
            stature_picker_view.snp.makeConstraints { (make) in
                make.left.bottom.right.equalTo(self.view)
                make.height.equalTo(ST_BTOncePickerView.height)
            }
        }
        
            self.stature_picker_view.isHidden = false
        
        guard let result =  queryItem(by: "height") else { return  }
        
        
        switch result.model {
        case .generalInfo(let value):
            
            let idx = stature_picker_view_datas.firstIndex { (str) -> Bool in
                return str == value.displayValue
            }
            
            if let index = idx{
                self.stature_picker_view.scroll_to_idx(Int(index))
            }
            
        default:
            break
        }
        
    }
    
    func select_home_town_action(){
    
        if self.homeTownPickerView.superview == nil {
        
            self.view.addSubview(self.homeTownPickerView)
                homeTownPickerView.snp.makeConstraints { (make) in
                    make.left.bottom.right.equalTo(self.view)
                    make.height.equalTo(ST_BTOncePickerView.height)
                }
        }
    
        self.homeTownPickerView.isHidden = false
    
    }
    
    
    @objc func select_birth_day_action(){
        
        if self.pickerView.superview == nil {
            
            self.view.addSubview(self.pickerView)
            pickerView.snp.makeConstraints { (make) in
                make.left.bottom.right.equalTo(self.view)
                make.height.equalTo(ST_BirthdayPickerView.height)
            }
            
        }
        
//        let value = self.data_array[2].infoValue
        if let date = self.birthDay{
            self.pickerView.setBirthDay(date: date)
        }
        
        
        
        self.pickerView.isHidden = false
        
    }
    
    @objc func home_town_pick_action(){
        
        
        guard let c = self.city ,let p = self.province else { return  }
        
        guard let result =  queryItem(by: "home_town_title") else { return  }
        
        
        
        self.modified_map.updateValue( p + " " + c, forKey: "home_town_title")
        
        self.save_modify_handle()
    
    
        
        switch result.model {
        case .generalInfo(let value):
            
            if self.data_array[safe: result.indexPath.section]?[safe: result.indexPath.item] != nil{
                
                self.data_array[result.indexPath.section][result.indexPath.item] = ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: value.displayKey, displayValue: p == c ? p : p + " " + c, modifyKey: value.modifyKey))
                
                self.tableView.reloadData()
                
            }
        default:
            break
        }
        
    }
    
    
    @objc func birthday_pick_action(date:Date){
        
        let formatter = DateFormatter()
        //日期样式
        formatter.dateFormat = "yyyy/MM/dd"
        
        let formatterValue = formatter.string(from: date)
        
        self.birthDay = date
        
        self.modified_map.updateValue( formatterValue , forKey: "birth")
        
        self.save_modify_handle()
    
        guard let result =  queryItem(by: "birth") else { return  }
        
        switch result.model {
        
        case .generalInfo(let value):
            
            if self.data_array[safe: result.indexPath.section]?[safe: result.indexPath.item] != nil{
                
                self.data_array[result.indexPath.section][result.indexPath.item] = ST_EditMyInfoCellData.generalInfo(value: ST_EditGeneralInfoCellModel_Copy(displayKey: value.displayKey, displayValue: formatterValue, modifyKey: value.modifyKey))
                
                self.tableView.reloadData()
                
            }
        default:
            break
        }
    }
    
    
    
}
//MARK: - Modify Header album
extension ST_EditMyInfoViewController{
    
    /**
     添加照片视频
     */
    func append(model:ST_PairsShareParticularModel) {
        
        self.album.append(model)
        
        self.headerView.setUp(data_array: album)
        
    }
    
    /**
     根据 url_array 排序，没有包括的URL 删除
     */
    func sort(by url_array:[String]){
        
        var tempArray = [ST_PairsShareParticularModel]()
        
        for url in url_array{
            
            let find = album.first { (m) -> Bool in
                return m.imageUrl == url
            }
            
            if let fItem = find{
                tempArray.append(fItem)
            }
        }
        
        self.album = tempArray
        
        if let first = self.album.first{
            
            self.header_height = first.displayHeight
            
        }
    }
    
    
}

//MARK: - interactive Header Height
extension ST_EditMyInfoViewController:ST_PairsShareParticularViewDelegate{
    
    func PHScrollViewDidScroll(_ scrollView: UIScrollView, viewHeight: CGFloat) {
        
        self.header_height = viewHeight
         
        
    }
    
    func PHScrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
    }
    
    
    
    
    
}
